package net.oschina.renyong.query.generator;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.IDbQuery;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;

import net.oschina.renyong.query.generator.po.ContentField;

/**
 * 表的解析器
 * @author Timothy
 */
public class TblParser {

	/**
	 * 解析数据表并填充对应的查询字段信息
	 * @param tblName 表名
	 * @param contentFieldByTblColumnMap 表名字段名-字段信息MAP
	 * @param globalConfig 全局配置
	 * @param dataSourceConfig 数据库配置
	 * @param connection 数据库连接
	 */
	public static void parseTblAndFillColumn(String tblName, Map<String, ContentField> contentFieldByTblColumnMap,
			GlobalConfig globalConfig, DataSourceConfig dataSourceConfig, Connection connection) {
		IDbQuery dbQuery = dataSourceConfig.getDbQuery();
		// 使用try-with-resources方式自动关闭PreparedStatement
		try (PreparedStatement preparedStatement = connection
				.prepareStatement(String.format(dbQuery.tableFieldsSql(), tblName))) {
			ResultSet results = preparedStatement.executeQuery();
			while (results.next()) {
				String columnName = results.getString(dbQuery.fieldName());
				DbColumnType dbColumnType = (DbColumnType) dataSourceConfig.getTypeConvert()
						.processTypeConvert(globalConfig, results.getString(dbQuery.fieldType()));
				String tblColumn = tblName + "," + columnName;
				ContentField contentField = contentFieldByTblColumnMap.get(tblColumn);
				if (contentField != null) {
					contentField.setColumnType(dbColumnType);
				}
			}
		} catch (SQLException e) {
			System.err.println("SQL Exception：" + e.getMessage());
		}
	}

}
